<?php

/*

COMP 353F
Dr. B Desai
Final Project
Group #11

6330746 Nicholas CONSTANTINIDIS
9532862 Jacqueline FU
5484537 Claudio Javier LOPEZ FLORES
9218416 Que Tung NGUYEN

*/

  session_start();
?>

<!DOCTYPE html>
<html lang="en">
<head>
        <title>CoBAGSys - Home</title>
        <link type="text/css" rel="stylesheet" href="css/mystyle.css">
        <script type="text/JavaScript" src="js/validate.js"></script>
        <script type="text/JavaScript">
        <!--
        function ValidateBidFields() {
	        return ValidateFieldNotEmpty("slick-login", "price", "price")
	        && ValidateFieldNumeric("slick-login", "price", "price");
        }
        
        function ValidateBarterFields() {
	        return ValidateFieldNotEmpty("slick-login", "description", "description");
        }        
        //-->
        </script>
</head>
<body>
    <?php
      require 'menus.php';
    ?>
    <?php
		// Create the new bid
		function bid() {
			$db = new Connect();
			
			$price = 0;
			if (isset($_POST['price']))
				$price = $_POST['price'];
			$desc = "";
			if (isset($_POST['description']))
				$desc = $_POST['description'];
			
			$sql = "INSERT INTO Transaction(email, pID, tDatetime, tDesc, price, tCity) " .
				   "SELECT email, " . $_GET['pid'] . ", now(), '" . $desc . "', " . $price . ", mCity " .
				   "FROM MemberInfo " .
				   "WHERE mID = " . $_SESSION['mid'];
			
			$result = $db->query($sql);
			
			if(!$result || mysql_affected_rows() == 0) // Failed posting bid
			{
				return false;
			}
			else // Bid posted
			{
				return true;
			}
		}
		
    	// Get the posting information
		function getPosting() {
			$db = new Connect();
			
			$sql = "SELECT pName, img, mID, status " .
				   "FROM Posting " .
				   "WHERE pID = " . $_GET['pid'];
				   
			$result = $db->query($sql);
			
			if(!$result || mysql_num_rows($result) == 0) // Couldn't find posting
			{
				return;
			}
			else // Return posting info
			{
				$rows = $db->to_array($result);
				return $rows[0];
			}
		}
    	
    	// Returns the search results from the bids table
    	function getBids() {
			$db = new Connect();

			$sql = "SELECT tID, price, tDesc, tDatetime, final FROM Transaction " .			
				   "WHERE pid = " . $_GET["pid"] .
				   " ORDER BY price DESC, tDatetime DESC";
			
			$result = $db->query($sql);
			
			if(!$result || mysql_num_rows($result) == 0)
			{
				return;
			}
			else
			{
				$rows = $db->to_array($result);
				return $rows;
			}
    	}
    	
		// Check to see if we received post data and perform bid
		$bid_failed = false;
		if (isset($_POST["bid"]))
			$bid_failed = !bid();
    ?>
    <div id="main">
<?php
	$posting = getPosting();
	
	if (!isset($posting))
	{
		print "<p></p><span class=\"error\">INVALID POSTING SPECIFIED!</span>";
	}
	else
	{
	    print "<p class=\"title\">";
	    if ($posting['status'] == "Open" || $posting['status'] == "Closed")
	    	print "Bidding";
	    else
	    	print "Bartering";
		print "</p>";
		
		print "<p class=\"normal\">";
		print $posting['pName'] . "<br/>";
		print "<img src=\"" . $posting['img'] . "\" height=\"100px\" width=\"100px\" alt=\"Image\"/>";
		print "</p>";
		
		$rows = getBids();
		if (isset($rows))
		{
		    if ($posting['status'] == "Open" || $posting['status'] == "Closed")
				print "<p class=\"title\">Current bids:</p>";
			else
				print "<p class=\"title\">Current offers:</p>";
			print "<table border=\"0\">";
			print "<tr>";
		    if ($posting['status'] == "Open" || $posting['status'] == "Closed")
				print "<th class=\"normal\">Price</th>";
			else
				print "<th class=\"normal\">Description</th>";
			print "<th class=\"normal\">Date</th>";
			print "</tr>";
			
			$rowcount = count($rows);
			for ($i = 0; $i < $rowcount; $i++)
			{
				print "<tr>";
			    if ($posting['status'] == "Open" || $posting['status'] == "Closed")
					print "<td class=\"legal\">" . $rows[$i]['price'] . "$</td>";
				else
					print "<td class=\"legal\">" . $rows[$i]['tDesc'] . "</td>";
				print "<td class=\"legal\">" . $rows[$i]['tDatetime'] . "</td>";
				if (isLoggedIn() && $posting['mID'] == $_SESSION['mid'] && $posting['status'] == "Open")
					print "<td><input type=\"button\" class=\"smallButton\" value=\"Accept\" onclick=\"parent.location='acceptbid.php?bid=" . $rows[$i]['tID'] . "&pid=" . $_GET['pid'] . "'\"/></td>";
				else if (isLoggedIn() && $posting['mID'] == $_SESSION['mid'] && $posting['status'] == "Barter")
					print "<td><input type=\"button\" class=\"smallButton\" value=\"Accept\" onclick=\"parent.location='acceptbid.php?bbid=" . $rows[$i]['tID'] . "&pid=" . $_GET['pid'] . "'\"/></td>";
				if ($rows[$i]['final'])
					print "<td class=\"error\">ACCEPTED</td>";
				print "</tr>";
			}
			
			print "</table>";
		}
	}
?>
<?php
	$validationFunction = "ValidateBidFields()";
	if ($posting['status'] == "Barter")
		$validationFunction = "ValidateBarterFields()";

    // We need to keep the pid value from disappearing
	print "<form id=\"slick-login\" onsubmit=\"return " . $validationFunction . ";\" action=\"bid.php?pid=" . $_GET['pid'] . "\" method=\"post\">";

	if ($bid_failed == true)
		print "<p class=\"error\">FAILED MAKING BID!</p>";
		
	if ($posting['status'] == "Open")
	{
		print "<p class=\"title\">New bid</p>";
		print "<input type=\"text\" name=\"price\" placeholder=\"Price\">";
		print "<p></p>";
		print "<input type=\"submit\" name=\"bid\" value=\"Make bid\">";
	}
	else if ($posting['status'] == "Barter")
	{
		print "<p class=\"title\">New offer</p>";
		print "<input type=\"text\" name=\"description\" placeholder=\"Description\">";
		print "<p></p>";
		print "<input type=\"submit\" name=\"bid\" value=\"Make offer\">";
	}
?>
		</form>
    </div>
</body>
</html>